package com.service.edu.listenter;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.base.exception.MyException;
import com.service.edu.pojo.Subject;
import com.service.edu.pojo.excel.SubjectData;
import com.service.edu.service.SubjectService;

import java.util.Date;

public class ExcelSubjectReadListenter extends AnalysisEventListener<SubjectData> {

  private SubjectService subjectService;

    public ExcelSubjectReadListenter(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        System.out.println(subjectData);
        if (subjectData==null){
            throw  new MyException(20001,"数据为空");
        }
        //查询一级分类是否存在
        Subject subject = exitOneSubject(subjectService,subjectData.getOneSubject());
        //如果不存在则添加
        if (subject==null){
            subject  = new Subject();
            subject.setGmtCreate(new Date());
            subject.setGmtModified(new Date());
            subject.setTitle(subjectData.getOneSubject());
            subjectService.save(subject);
        }
        //查询二级分类是否存在
        Subject twoSubject = exitTwoSubject(subjectService,subjectData.getTwoSubject(),subject.getId());
        //如果不存在则添加
        if (twoSubject==null){
            twoSubject  = new Subject();
            twoSubject.setGmtCreate(new Date());
            twoSubject.setGmtModified(new Date());
            twoSubject.setTitle(subjectData.getTwoSubject());
            twoSubject.setParentId(subject.getId());
            subjectService.save(twoSubject);
        }
    }

    public Subject exitOneSubject(SubjectService subjectService,String title) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        return  subjectService.getOne(queryWrapper);
    }


    public Subject exitTwoSubject(SubjectService subjectService,String title, String pid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",pid);
        return  subjectService.getOne(queryWrapper);
    }




    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
